package com.naizhuai.ui.task.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.exception.ValidateException;
import com.naizhuai.ui.adapter.GridSpacingItemDecoration;
import com.naizhuai.ui.entity.ImgBean;
import com.naizhuai.ui.entity.Task.FlowMethodDetial;
import com.naizhuai.ui.entity.Task.UploadFlow;
import com.naizhuai.ui.entity.UserLeader;
import com.naizhuai.ui.task.deliverentity.TaskType;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.AlbumUtils;
import com.naizhuai.util.BitmapUtils;
import com.naizhuai.util.ToastCompat;
import com.naizhuai.util.ViewUtils;
import com.yanzhenjie.album.AlbumFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * @author：lichenxi
 * @date 2018/3/15 17
 * email：525603977@qq.com
 * Fighting
 */
public class StepListAdapter extends RecyclerView.Adapter<StepListAdapter.ViewHolder> {
    List<FlowMethodDetial> mFlowListBeans;

    List<FlowSelectLoader> mSelectLoaders;
    List<TaskTypeAdapter> mTaskTypeAdapters;
    List<TaskExplainAdapter> mExplainAdapters;

    private List<TaskType> circleTypeList;

    private List<UserLeader> managerList;

    public void setTypeData(List<TaskType> circleTypeList, List<UserLeader> managerList) {
        this.circleTypeList = circleTypeList;
        this.managerList = managerList;
    }

    private TaskTypeAdapter mFlowAdapter;

    public StepListAdapter() {

    }

    public void setFlowList(List<FlowMethodDetial> flowListBeans) {
        mFlowListBeans = flowListBeans;
        mSelectLoaders = new ArrayList<>(flowListBeans.size());
        mTaskTypeAdapters = new ArrayList<>(flowListBeans.size());
        mExplainAdapters = new ArrayList<>(flowListBeans.size());
    }

    public void addFlow(FlowMethodDetial flowMethodDetial) {
        mFlowListBeans.add(flowMethodDetial);
        notifyItemInserted(mFlowListBeans.size());
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_step_list, parent, false);
        return new ViewHolder(view);
    }

    // 负责人 选择任务周期 描述详情
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Context context = holder.itemView.getContext();
        FlowMethodDetial flowMethodDetial = mFlowListBeans.get(holder.getAdapterPosition());

        holder.number.setText(flowMethodDetial.step);
        holder.edStepName.setText(flowMethodDetial.flowName);

        //选择负责人
        holder.selectLeaderList.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        FlowSelectLoader selectLoader = new FlowSelectLoader(managerList);
        holder.selectLeaderList.setAdapter(selectLoader);
        mSelectLoaders.add(holder.getAdapterPosition(), selectLoader);

        //选择周期 每次进行深度拷贝 保证指向不同的内存地址
        ArrayList arrayList = new ArrayList(circleTypeList.size());
        Iterator<TaskType> iterator = circleTypeList.iterator();
        while (iterator.hasNext()) {
            arrayList.add(iterator.next().clone());
        }

        TaskTypeAdapter mTaskCircleTypeAdapter = new TaskTypeAdapter(arrayList);
        mTaskCircleTypeAdapter.setSelected(TaskTypeAdapter.SERIALSELECTED);

        GridLayoutManager layoutManager = new GridLayoutManager(context, 4, GridLayoutManager.VERTICAL, false);

        holder.cycleSelect.setNestedScrollingEnabled(false);
        holder.cycleSelect.setLayoutManager(layoutManager);
        holder.cycleSelect.addItemDecoration(new GridSpacingItemDecoration(4, context.getResources().getDimensionPixelSize(R.dimen.padding_default_min), false));
        holder.cycleSelect.setAdapter(mTaskCircleTypeAdapter);

        mTaskTypeAdapters.add(holder.getAdapterPosition(), mTaskCircleTypeAdapter);

        //每次变化的部分
        ViewUtils.showImg(flowMethodDetial.imageUrl, holder.editImg);
        holder.editImg.setOnClickListener(v ->
                AlbumUtils.singleChoice(context)
                        .subscribe(albumFile ->{
                            holder.progressImg.setVisibility(View.VISIBLE);
                            Observable.just(albumFile.getPath())
                                    .map(imagepath -> {
                                        //通过这个Path 压缩图片 并且返回压缩图片的路径 然后下发
                                        Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
                                        File file = BitmapUtils.changeBitmap2File(bitmap, context, "temp.jpeg");
                                        return file.getPath();
                                    })
                                    .flatMap(imagepath -> UserManageDataApiStoreIml.getInstance().uploadImg(imagepath))
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new NetWorkObserver<ImgBean>() {
                                        @Override
                                        protected void onFail(String errormsg) {
                                            holder.progressImg.setVisibility(View.GONE);
                                            ToastCompat.showToast(context, "图片上传失败", Toast.LENGTH_SHORT);
                                        }

                                        @Override
                                        protected void onSuccess(ImgBean result) {
                                            holder.progressImg.setVisibility(View.GONE);
                                            ViewUtils.showImg(result.getImgUrl(), holder.editImg);
                                            flowMethodDetial.imageUrl = result.getImgUrl();
                                        }
                                    });
                        } )

        );

//        ArrayList<String> strings=new ArrayList(flowMethodDetial.detail.size());
//        Iterator<String> iteratora = flowMethodDetial.detail.iterator();
//        while(iterator.hasNext()){
//            strings.add(iteratora.next().clone());
//        }

        ArrayList<String> strings = new ArrayList(flowMethodDetial.detail);
        TaskExplainAdapter mTaskExplainAdapter = new TaskExplainAdapter(strings);

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        holder.editlist.setLayoutManager(layoutManager1);
        holder.editlist.setAdapter(mTaskExplainAdapter);
        mExplainAdapters.add(holder.getAdapterPosition(), mTaskExplainAdapter);
    }

    public List<UploadFlow> getUploadFlow(Context context) throws Exception {
        ArrayList<UploadFlow> temp = new ArrayList<>();
        for (int i = 0; i < mFlowListBeans.size(); i++) {
            FlowMethodDetial flowMethodDetial = mFlowListBeans.get(i);
            String uid = mSelectLoaders.get(i).getSelectUid();
            if (TextUtils.isEmpty(uid)) {
                //处理空的情况 step_noselect
                throw new ValidateException(context.getResources().getString(R.string.step_noselect, flowMethodDetial.step)
                        + context.getResources().getString(R.string.chose_no_user));
            }
            List<TaskType> taskTypes = mTaskTypeAdapters.get(i).getSelected();
            if (taskTypes.isEmpty()) {
                //处理没有选择情况
                throw new ValidateException(context.getResources().getString(R.string.step_noselect, flowMethodDetial.step)
                        + context.getResources().getString(R.string.taskcircletype_not_null));
            }
            String detial = mExplainAdapters.get(i).getTaskString();
            if (TextUtils.isEmpty(detial)) {
                //处理空的情况
                throw new ValidateException(context.getResources().getString(R.string.step_noselect, flowMethodDetial.step)
                        + context.getResources().getString(R.string.task_please_input_flowdetial));
            }
            UploadFlow flow = new UploadFlow()
                    .setFlowName(flowMethodDetial.flowName)
                    .setStep(flowMethodDetial.step)
                    .setImageUrl(flowMethodDetial.imageUrl)
                    .setDetail(detial)
                    .setCycleTypes(taskTypes)
                    .setLeadUid(uid);
            temp.add(flow);
        }

        return temp;
    }

    @Override
    public int getItemCount() {
        return mFlowListBeans != null ? mFlowListBeans.size() : 0;
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.number)
        TextView number;
        @BindView(R.id.ed_step_name)
        EditText edStepName;
        @BindView(R.id.select_leader_list)
        RecyclerView selectLeaderList;
        @BindView(R.id.cycle_select)
        RecyclerView cycleSelect;
        @BindView(R.id.editImg)
        ImageView editImg;
        @BindView(R.id.editlist)
        RecyclerView editlist;
        @BindView(R.id.progress_img)
        ProgressBar progressImg;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

}
